package controllers

import (
	"demo/models"
	"demo/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/prometheus/common/log"
	"time"
)

type RegisterController struct {
	beego.Controller
}

func (register *RegisterController) Post()  {
	//获取表单信息
	username 	:= register.GetString("username")
	password 	:= register.GetString("password")
	repassword 	:= register.GetString("repassword")

	fmt.Println(username, password, repassword)
	log.Info(username, password, repassword)

	//注册之前先判断用户名是否已经被注册，如果已经注册，返回错误
	id := models.QueryUserWithUsername(username)
	fmt.Println("id：", id)
	if id > 0 {
		register.Data["json"] = map[string]interface{}{"code":0, "message": "用户名已经存在"}
	}

	//注册用户名和密码
	password = utils.MD5(password)
	fmt.Println("md5后：", password)

	user := models.Users{0, username, password, 0, time.Now().Unix()}
	_, err := models.InsertUser(user)
	if err != nil {
		register.Data["json"] = map[string]interface{}{"code": 0, "message": "注册失败"}
	}else{
		register.Data["json"] = map[string]interface{}{"code": 1, "message": "注册成功"}
	}
	register.ServeJSON()
}
